<template>
    <WidgetContainer :widget-id="config.id">
        <div v-show="!config.attributes.hidden" class="row-flex-container" :class="config.attributes?.cssClass" :style="flexStyle">
            <draggable v-model="config.children" group="form" item-key="id" @add="onAdd" class="row-flex-draggable" :animation="150">
                <template #item="{ element }">
                    <component :is="designer.renderComponent(element)" :config="element" />
                </template>
            </draggable>
        </div>
    </WidgetContainer>
</template>

<script setup>
import { inject, computed } from 'vue';
import draggable from 'vuedraggable';

const props = defineProps({
    config: {
        type: Object,
        required: true
    }
});

const designer = inject('designer');
const selectWidgetId = inject('selectWidgetId')

const onAdd = (evt) => {
    selectWidgetId.value = evt?.item?._underlying_vm_?.id || selectWidgetId.value
};

const flexStyle = computed(() => {
    const { justify, align, gap, wrap } = props.config.attributes;
    return {
        display: 'flex',
        flexWrap: wrap ? 'wrap' : 'nowrap',
        justifyContent: mapJustify(justify),
        alignItems: mapAlign(align),
        gap: gap || '10px'
    };
});

function mapJustify(val) {
    return {
        start: 'flex-start',
        center: 'center',
        end: 'flex-end',
        'space-between': 'space-between',
        'space-around': 'space-around'
    }[val] || 'flex-start';
}

function mapAlign(val) {
    return {
        start: 'flex-start',
        center: 'center',
        end: 'flex-end'
    }[val] || 'flex-start';
}
</script>

<style scoped>
.row-flex-container {
    border: 1px dashed #999;
    padding: 5px;
    box-sizing: border-box;
    margin: 5px 0;
}

.row-flex-draggable {
    display: flex;
    flex-wrap: inherit;
    gap: inherit;
    width: 100%;
    min-height: 80px;
}
</style>